package com.yc.thread.pc;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

// 实现一个简单的生产者和消费者模型
public class ProductConsumerNew {
    public static void main(String[] args){

        Source s = new Source();
        // 线程A 生产
        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                try {
                    s.increment();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "A").start();

        // 线程B 消费
        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                try {
                    s.decrement();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "B").start();
    }
}

// 定义资源
class SourceNew{
    private int number = 0;

    // 拿到一个锁
    Lock lock = new ReentrantLock();
    Condition condition = lock.newCondition();

    // 生产
    public  void increment() throws InterruptedException {
        while (number != 0) {
            condition.await();
        }
        number ++;
        System.out.println(Thread.currentThread().getName() + "生产了！存货为：" + number);
        condition.signalAll();
    }
    // 消费
    public synchronized void decrement() throws InterruptedException {
        while (number == 0) {
            condition.await();
        }
        number --;
        System.out.println(Thread.currentThread().getName() + "消费了！存货为：" + number);
        condition.signalAll();
    }
}
